<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="科室" prop="departmentCode">
        <el-select
          v-model="queryParams.departmentCode"
          placeholder="请选择科室"
          clearable
        >
          <el-option
            v-for="dict in td_department"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="医生姓名" prop="docterName">
        <el-input
          v-model="queryParams.docterName"
          placeholder="请输入医生姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生编码" prop="docterCode">
        <el-input
          v-model="queryParams.docterCode"
          placeholder="请输入医生编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="注册时间" prop="createTime">
        <el-date-picker
          clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择注册时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 卡片式布局 -->
    <el-row :gutter="20" v-loading="loading">
      <el-col
        v-for="doctor in docterlistList"
        :key="doctor.docterId"
        :xs="24"
        :sm="12"
        :md="8"
        :lg="6"
        class="doctor-card-col"
      >
        <el-card class="doctor-card" shadow="hover">
          <div class="card-content">
            <!-- 根据性别显示头像 -->
            <div class="avatar-wrapper">
              <el-avatar :size="80">
                <img
                  v-if="doctor.sex === '1'"
                  src="/src/assets/images/womandoctor.jpg"
                />
                <img
                  v-else-if="doctor.sex === '0'"
                  src="/src/assets/images/mandoctor.jpg"
                />
                <img v-else src="/src/assets/images/doctor.jpg" />
              </el-avatar>
            </div>

            <!-- 基本信息 -->
            <div class="info-wrapper">
              <div class="name-code">
                <span class="name">{{ doctor.docterName }}</span>
                <!-- <el-tag type="info" size="small"
                  >医生编码: {{ doctor.docterCode }}</el-tag
                > -->
              </div>

              <div class="department" style="display: flex">
                所属科室:
                <dict-tag
                  :options="td_department"
                  :value="doctor.departmentCode"
                  type="primary"
                />
              </div>

              <div class="details">
                <div class="detail-item">
                  <i class="el-icon-user"></i>
                  职位:
                  <span>{{ doctor.title || "暂无职称" }}</span>
                </div>
                <div class="detail-item">
                  <i class="el-icon-phone"></i>
                  联系电话:
                  <span>{{ doctor.phone || "暂无电话" }}</span>
                </div>
                <div class="detail-item">
                  <i class="el-icon-office-building"></i>
                  所属部门:
                  <span>{{ doctor.deptName || "暂无部门" }}</span>
                </div>
                <div class="detail-item">
                  <i class="el-icon-user-solid"></i>
                  <span>{{ doctor.userName }}</span>
                </div>
                <div class="action-area" v-if="!doctor.userName">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleAddzh(doctor)"
                    class="create-btn"
                  >
                    <i class="el-icon-user-add"></i>
                    创建账号
                  </el-button>
                </div>
              </div>

              <div class="footer">
                <el-text type="info" size="small">
                  注册时间：{{ parseTime(doctor.createTime, "{y}-{m}-{d}") }}
                </el-text>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- <el-table v-loading="loading" :data="docterlistList" @selection-change="handleSelectionChange">
      <el-table-column label="医生姓名" align="center" prop="docterName" />
      <el-table-column label="医生编码" align="center" prop="docterCode" />
      <el-table-column label="科室" align="center" prop="departmentCode">  
        <template #default="scope">
          <dict-tag :options="td_department" :value="scope.row.departmentCode"/>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center" prop="phone"/>
      <el-table-column label="职称" align="center" prop="title"/>
      <el-table-column label="医生账号用户名" align="center" prop="userName"/>
      <el-table-column label="部门" align="center" prop="deptName"/>
      <el-table-column label="注册时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
    </el-table> -->

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改医生信息对话框
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="docterlistRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="科室" prop="departmentCode">
          <el-select v-model="form.departmentCode" placeholder="请选择科室">
            <el-option
              v-for="dict in td_department"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医生姓名" prop="docterName">
          <el-input v-model="form.docterName" placeholder="请输入医生姓名" />
        </el-form-item>
        <el-form-item label="医生编码" prop="docterCode">
          <el-input v-model="form.docterCode" placeholder="请输入医生编码" />
        </el-form-item>
        <el-form-item label="医生年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入医生年龄" />
        </el-form-item>
        <el-form-item label="医生电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入医生电话" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog> -->

    <!-- 添加账号弹窗 -->
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input
                v-model="form.nickName"
                placeholder="请输入用户昵称"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <el-tree-select
                v-model="form.deptId"
                :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="请选择归属部门"
                check-strictly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="form.phonenumber"
                placeholder="请输入手机号码"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入邮箱"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              v-if="form.userId == undefined"
              label="账号"
              prop="userName"
            >
              <el-input
                v-model="form.userName"
                placeholder="请输入账号"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="form.userId == undefined"
              label="用户密码"
              prop="password"
            >
              <el-input
                v-model="form.password"
                placeholder="请输入用户密码"
                type="password"
                maxlength="20"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option
                  v-for="dict in sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-select v-model="form.postIds" multiple placeholder="请选择">
                <el-option
                  v-for="item in postOptions"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select v-model="form.roleIds" multiple placeholder="请选择">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 医生选择区域 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="绑定医生" prop="doctorId">
              <!-- 移除 el-select，改为隐藏输入框或其他形式 -->
              <el-input type="hidden" v-model="form.docterId" />
              <span>{{ form.docterName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Docterlist">
import {
  listDocterlist,
  delDocterlist,
} from "@/api/docters/docterlist";

import { getUser, deptTreeSelect, updateUser, addDocterUser } from "@/api/system/user";

const { proxy } = getCurrentInstance();
const { td_department } = proxy.useDict("td_department");

const docterlistList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const postOptions = ref([]);
const roleOptions = ref([]);
const initPassword = ref(undefined);
const deptName = ref("");
const deptOptions = ref(undefined);
const data = reactive({
  form: {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    postIds: [],
    roleIds: [],
    docterId: undefined, // 添加医生 ID 字段
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    departmentCode: null,
    docterName: null,
    docterCode: null,
    createTime: null,
  },
  rules: {
    userName: [
      { required: true, message: "账号不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "账号长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    nickName: [
      { required: true, message: "用户昵称不能为空", trigger: "blur" },
    ],
    password: [
      { required: true, message: "用户密码不能为空", trigger: "blur" },
      {
        min: 5,
        max: 20,
        message: "用户密码长度必须介于 5 和 20 之间",
        trigger: "blur",
      },
    ],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      },
    ],
    phonenumber: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
  },
});

const { sys_normal_disable, sys_user_sex } = proxy.useDict(
  "sys_normal_disable",
  "sys_user_sex"
);
// const { td_department } = proxy.useDict('td_department');

const { queryParams, form, rules } = toRefs(data);

/** 根据名称筛选部门树 */
watch(deptName, (val) => {
  proxy.$refs["deptTreeRef"].filter(val);
});
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data;
  });
}

// 创建账号操作
function handleAddzh(docter) {
  reset();
  console.log(docter);
  // 将 docter 的值赋给 form
  form.value.docterId = docter.docterId;
  form.value.docterName = docter.docterName;
  console.log("form",form);
  getUser().then((response) => {
    postOptions.value = response.posts;
    roleOptions.value = response.roles;
    open.value = true;
    title.value = "添加用户";
    form.value.password = initPassword.value;
  });
}

/** 查询医生信息列表 */
function getList() {
  loading.value = true;
  listDocterlist(queryParams.value).then((response) => {
    docterlistList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    docterId: null,
    departmentCode: null,
    docterName: null,
    docterCode: null,
    age: null,
    phone: null,
    createTime: null,
  };
  proxy.resetForm("docterlistRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      if (form.value.userId != undefined) {
        updateUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDocterUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _docterIds = row.docterId || ids.value;
  proxy.$modal
    .confirm('是否确认删除医生信息编号为"' + _docterIds + '"的数据项？')
    .then(function () {
      return delDocterlist(_docterIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "docters/docterlist/export",
    {
      ...queryParams.value,
    },
    `docterlist_${new Date().getTime()}.xlsx`
  );
}
getDeptTree();
getList();
</script>

<style scoped>
.doctor-card-col {
  margin-bottom: 20px;
  transition: transform 0.3s;

  &:hover {
    transform: translateY(-3px);
  }
}

.doctor-card {
  border-radius: 12px;
  border-width: 2px;
  transition: all 0.3s ease;
  overflow: hidden;
  height: 400px; /* 固定卡片高度 */

  &:hover {
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1);
  }

  .card-content {
    padding: 15px;
    position: relative;

    .avatar-wrapper {
      text-align: center;
      margin-bottom: 20px;
      img {
        border-radius: 50%;
      }
    }

    .name-code {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      .name {
        font-size: 18px;
        font-weight: 400;
        letter-spacing: 0.5px;
      }

      .el-tag {
        border: none;
        font-weight: 500;
      }
    }

    .department {
      margin-bottom: 15px;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .details {
      .detail-item {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        font-size: 13px;

        i {
          font-size: 16px;
          margin-right: 10px;
          width: 20px;
          text-align: center;
        }

        span {
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    .action-area {
      margin-top: 20px;
      text-align: center;

      .create-btn {
        width: 100%;
        border-radius: 8px;
        padding: 10px;
        font-weight: 500;
        letter-spacing: 0.5px;
      }
    }

    .footer {
      margin-top: 15px;
      padding-top: 12px;
      border-top: 1px dashed #eee;
      font-size: 12px;
      color: #909399;
    }
  }
}
</style>
